Util.DataGridEditRow = function(dataGrid, oConfig, callbacks){
    this.grid = dataGrid;
    this.el =  null;
    this.row = null;
	this.addRow = null;
    this.cfg = {
        showOnClick: true,
        showOnDBclick: false,
        showButtons: true,
        autoSave: true,
        showAtTop: true,
        autoAddRow: true
    };
    $.extend(true, this.cfg, oConfig);
    this.cb = {
        afterSave: function(isSucceed,editRowData){},
        afterAdd: function(isSucceed, rowData){},
        onShow: function(){}
    };
    $.extend(this.cb, callbacks);
    this._columnCfg = [];
    this.targetRow = null;
    this.blankRow = null;
    this.rowContainer = null;
    this.__newRowIdSeed = 0;
	this.addRowResizeAtFirstTime = true;
    this._init(); 
};
Util.DataGridEditRow.prototype = {
    _init: function(){
        //this.blankRow = $('<div class="rtq-grid-enptyrow"></div>').prependTo(this.grid.el.find('.rtq-grid-scroll'));
        this._columnCfg = this._createColumnCfg(this.grid.cfg.column);
        this._createEditRow(this.grid.el.find('.rtq-grid-scroll'));
        var self = this;
        if (this.cfg.showOnClick) {
//            this.grid.bind('rowSelected', function(e, row){
//                if (self.cfg.autoSave) {
//                    self.save();
//                }
//                self.show(row);
//            });
        }
        if (this.cfg.showOnDBclick) {
//            this.grid.bind('rowDoubleClick', function(e, row){
//                if (self.cfg.autoSave) {
//                    self.save();
//                }
//                self.show(row);
//            });
        }
	   this.show(this.grid.header.row);
	   this.hide();
//        if (this.cfg.showAtTop) {
//            this.el.addClass('rtq-grid-editrow-addable');
//            this.blankRow = new Util.DataRow(this.el, this._columnCfg, {}, 'QS_EditRow_BlankRow', null, 'div');
//            this.blankRow.el.addClass('rtq-grid-enptyrow').click(function(e){
//                self.resetAddingRow();
//            });
//            this.blankRow.el.append("<div style='font-weight:bold;line-height:20px;'>Click here to add a new alert.</div>");
//            this.resetAddingRow();
//        }
    },
    _createColumnCfg: function(column){
        $.extend(true, this._columnCfg, column);
        for (var i = 0; i < this._columnCfg.length; i++) {
            this._columnCfg[i].renderer = null;
        }
        return this._columnCfg;
    },
    _editorController: {
        text: function(container, editorCfg){
            this.control = $('<input type="text" class="qs-ui-ipt">').appendTo(container);
            this.getValue = function(){
                return this.control.val();
            };
            this.setValue = function(v, w){
				if(v!=null){
					this.control.val(v)
				}
                this.control.width(w);
            }
        },
        dropdownlist: function(container, editorCfg){
            this.control = new Util.DropDownList(container, function(t, v){
            }, editorCfg.data,{triggerByClick:true,showScrollbar:true,ellipsis:false},$(".qs-alert .rtq-grid .rtq-grid-scroll"));
            this.getValue = function(){
                return this.control.getValue();
            };
            this.setValue = function(v, w){
				var tempData = this.control.data;
                    var selectedIndex =-1;
					if(typeof(v)!="undefined"&&v!=null){
						v = v.replace("&gt;",">").replace("&lt;","<");
					}
                    for(var i =0;i<tempData.length;i++){
                        if(tempData[i].val==v){
                            selectedIndex=i;
                            break;
                        }
                   }
                if (selectedIndex!=-1) {
                    //this.control.selectItemByIndex(selectedIndex);
					this.control.selectItemByValue(v);
                }
				if(!v){
					this.control.setTextValue(v);
				}
            }
        },
        checkbox: function(container, editorCfg){
            this.control = new Util.ButtonGroup(container, editorCfg.data ||
            [{
                txt: '',
                val: 'true'
            }], {
                onClick: function(v){
                }
            }, {
                type: 'checkbox'
            });
            
            this.getValue = editorCfg.getValue ? function(){
                return editorCfg.getValue.apply(this.control.btns['true'], [this.control.btns['true'].isSelected]);
            }
            : function(){
                return this.control.btns['true'].isSelected  ;
            };
            
            this.setValue = editorCfg.setValue ? function(){
                editorCfg.setValue.apply(this.control.btns['true'], arguments);
            }
            : function(value){
				if(value==true||value.indexOf("qs-datagrid-cell-checked")!=-1){
					this.control.btns['true'].select();
				}else{
					this.control.btns['true'].inverse();
				}
//                if (value.toLowerCase().indexOf('checked') > -1) {
//                    this.control.btns['true'].select();
//                }
//                else {
//                    this.control.btns['true'].inverse();
//                }
            }
        },
        custom: function(container, editorCfg,host){
            this.control = editorCfg.renderer(container);
            this.getValue = function(){
                return editorCfg.getValue.apply(this.control, arguments);
            };
            this.setValue = function(){
                editorCfg.setValue.apply(this.control, arguments);
            }
        }
    },
    _createEditRow: function(container){
        var self = this;
        this.el = $('<div class="rtq-grid-editrow-wrap"><div class="rtq-grid-editrow"><div class="row"></div></div></div>').prependTo(container).width(this.grid.body.width());
        this.rowContainer = this.el.children('.rtq-grid-editrow');
        if (this.cfg.showButtons) {
            this.rowContainer.append('<div class="btn"><a href="#" val="ok" class="qs-alert-button-style">Save</a><a val="cancel" href="#" class="qs-alert-button-style">Cancel</a></div>').hover(function(e){
                self.el.addClass('rtq-grid-editrow-over');
            },function(e){
                self.el.removeClass('rtq-grid-editrow-over');
            }).find('.qs-alert-button-style').click(function(e){
                if(this.getAttribute('val') == 'ok'){
//                    if (self.targetRow.id == self.blankRow.id) { //add
//                        self.add();
//                    }else{
                        self.save();
                   // }
                }else{
                    self.cancel();
                }
            });
        }
        this.row = new Util.DataRow(this.rowContainer.children('.row'), this._columnCfg, {}, 'QS_EditRow', null, 'div');
		var addrow = new Util.DataRow(this.cfg.addRowEl, this._columnCfg, {}, 'QS_addRow', null, 'div');
		var addTitleEl =this.cfg.addRowEl.find(".qs-alert-addrow-title-wrap");
        this._columnCfg = this.grid.cfg.column;
        var col, cell;
        for (var i = 0; i < this._columnCfg.length; i++) {
            col = this._columnCfg[i];
            this.row.cells[col.dataIndex].innerDom.innerHTML = '';
            if (col.editor) {
				if(typeof(col.editor.addAble)=="undefined"||col.editor.addAble===true){
					col.addObj=new self._editorController[col.editor.type](addrow.cells[col.dataIndex].innerDom, col.editor,this);
					col.addTitleObj = $("<div class='title-cell "+(col.className?col.className:"")+"'>"+col.header+"</div>").appendTo(addTitleEl);
				}else{
					addrow.DOMMap[col.dataIndex].style.display="none";
				}
				col.editorObj = new self._editorController[col.editor.type](self.row.cells[col.dataIndex].innerDom, col.editor,this);
                //disable the editor
                if(col.editor.readonly == true){
                    col.disableMask = $('<div class="mask"></div>').appendTo(this.row.cells[col.dataIndex].el);
                }
            }else{
				if(this.cfg.addRowEl.find(".qs-alert-btn-add").length>0){
					addrow.DOMMap[col.dataIndex].style.display="none";
				}else{
                    $("<a href='javascript:void(0);' style='white-space:nowrap;' class='qs-ui-btn qs-alert-btn-add'>Add alert</a>").appendTo(addrow.DOMMap[col.dataIndex]).bind("click", function(){
                        self.add();
                    });
				}
			}
        }
		
		this.addRow = addrow;
    },
    _getNewRowId: function(){
        return 'QSEditROW_NEWROW_' + this.__newRowIdSeed++;
    },
	setEditRowWidth:function(width){
		this.rowContainer.css({
            width: width
        });
//		this.blankRow.el.css({
//            width: width-2
//        });
	},
	reSize:function(useHeader){
		this.addRowResizeAtFirstTime = true;
		var status = this.rowContainer[0].style.display;
		//if(typeof(useHeader)=="undefined"||useHeader===true||this.grid.data.length==0){
			this.show(this.grid.header.row,false);
//		}else{
//			this.show(this.grid.rows[this.grid.data[0].alertId]);
//		}
		
		this.rowContainer[0].style.display=status;
	},
    show: function(targetRow,showEditRow){
		if (typeof(showEditRow) == "undefined" && showEditRow !== false) {
             this.targetRow = targetRow;
        }
        var col, w, v;
        for (var i = 0; i < this._columnCfg.length; i++) {
            col = this._columnCfg[i];
            if (this.targetRow.cells) {
                w = this.targetRow.cells[col.dataIndex].el.width() - 8
//				if(this.targetRow.id == this.blankRow.id&&col.editor&&col.editor.defaultValue){
//					v = col.editor.defaultValue;
//				}else{
					v = this.targetRow.cells[col.dataIndex].getValue();
//				}
            }
            else {
                w = col.width;
                v = '';
            }
            if (col.editor) {
				if (typeof(showEditRow) == "undefined" && showEditRow !== false) {
					col.editorObj.setValue(v, w);
				}
				if(col.addObj&&this.addRowResizeAtFirstTime){
					if(col.editor.defaultValue){
						col.addObj.setValue(col.editor.defaultValue);//col.addObj.setValue(col.editor.defaultValue, w);
                    }else{
						//col.addObj.setValue("");//col.addObj.setValue("", w);
						col.addObj.setValue(null, w);
					}
					var width = this.grid.header.row.cells[col.dataIndex].el.width()-1;
					col.addTitleObj.css({width:this.grid.header.row.cells[col.dataIndex].el.width()-1});
					if(col.editor.type&&col.editor.type=="dropdownlist"){
						  col.editorObj.control.resize(width-10);
						  col.addObj.control.resize(width);
					}
				}
                //disable the editor
                if (col.editor.readonly == true) {
//                    if (this.targetRow.id == this.blankRow.id) {
//                        this.row.cells[col.dataIndex].el.removeClass('rtq-grid-editor-readonly');
//                    }
//                    else {
                        this.row.cells[col.dataIndex].el.addClass('rtq-grid-editor-readonly');
//                    }
                }
            }else if(col.blankWhenEditting){
				this.row.cells[col.dataIndex].innerDom.innerHTML="<div>&nbsp;</div>";
			} else {
                this.row.cells[col.dataIndex].innerDom.innerHTML = '<div class="readonly-txt">' + v + '</div>';
            }
        }
        //this.el.show();
        var top = this.targetRow.el.position().top + this.grid.scrollPanel.scrollTop;
        var left = this.targetRow.el.position().left;
        var width = this.targetRow.el.width() + 2;
		if(typeof(showEditRow)!="undefined"&&showEditRow===false){
			this.hide();
		}else{
            this.rowContainer.css({
                top: top,
                left: left,
                width: width
            });
			this.rowContainer.show();
            this.cb.onShow();
		}
        
        this.addRowResizeAtFirstTime = false;
    },
    add: function(){
        var col, w, v, isSucceed = true;
        var newRowData = {};
        for (var i = 0; i < this._columnCfg.length; i++) {
            col = this._columnCfg[i];
            if (col.editor&&col.addObj) {
                editCell = this.addRow.cells[col.dataIndex].innerDom;
                if (col.editor.validator) {
                    if (!col.editor.validator(col.addObj.getValue(editCell,true),"add")) {
                        isSucceed = false;
                        break;
                    }
                }
                newRowData[col.dataIndex] = col.addObj.getValue(editCell,true);
            }
        }
//        if (isSucceed && this.cfg.autoAddRow == true) {
//            var id = this._getNewRowId();
//            this.grid.addRow(newRowData, id, 0);
//            this.grid.rows[id].renderDOM();
//        }
		var self = this;
        this.cb.afterAdd(isSucceed, newRowData,function(){
			self.resetAddingRow();
		});
		if(isSucceed){
			//this.resetAddingRow();
		}
    },
    save: function(){
       // if (this.targetRow.id != this.blankRow.id) {
            if (this.targetRow && this.targetRow.el) { //edit
                var col, w, v, isSucceed = true,editRowData ={alertId:this.targetRow.id};
                for (var i = 0; i < this._columnCfg.length; i++) {
                    col = this._columnCfg[i];
                    if (col.editor) {
                        editCell = this.row.cells[col.dataIndex].innerDom;
                        if (col.editor.validator) {
                            if (!col.editor.validator(col.editorObj.getValue(editCell),"update")) {
                                isSucceed = false;
                                break;
                            }
                        }
                        editRowData[col.dataIndex]=col.editorObj.getValue(editCell);
                    }
                }
                var self =this;
				if (this.cb.afterSave) {
					this.cb.afterSave(isSucceed, editRowData, function(cbAlertId,cbAction){
//						var col, w, v, isSucceed = true, editRowData = {
//							alertId: self.targetRow.id
//						};
						for (var i = 0; i < self._columnCfg.length; i++) {
							col = self._columnCfg[i];
							if (col.editor) {
								editCell = self.row.cells[col.dataIndex].innerDom;
								if (col.editor.validator) {
									if (!col.editor.validator(col.editorObj.getValue(editCell),"update")) {
										isSucceed = false;
										break;
									}
								}
								var fillValue = col.editorObj.getValue(editCell);
								if(col.dataIndex=="value"){
                                    if (!isNaN(fillValue)) {
										var tempFillValue = parseFloat(fillValue).toFixed(2);
										if(tempFillValue!="NaN"){
											fillValue = tempFillValue;
										}
                                    }
								}
								if(cbAction&&cbAction.needClearCol&&cbAction.needClearCol.indexOf(col.dataIndex)!=-1){
									fillValue=" ";
								}
								if(typeof(col.renderer)=="function"){
									self.targetRow.cells[col.dataIndex].innerDom.innerHTML = fillValue;
								}else{
									self.targetRow.cells[col.dataIndex].innerDom.innerHTML = fillValue;
								}
							}
						}
						if (isSucceed) {
							self.hide();
							if (self.cfg.showAtTop) {
								//self.resetAddingRow();
							}
						}
					});
				}
            }
       // }
    },
    resetAddingRow: function(){
        this._emptyEditor();
        //this.show();
    },
    _emptyEditor: function(){
        for (var i = 0; i < this._columnCfg.length; i++) {
            if (this._columnCfg[i].addObj) {
				if(this._columnCfg[i].editor.defaultValue){
					this._columnCfg[i].addObj.setValue(this._columnCfg[i].editor.defaultValue);
				}else{
					this._columnCfg[i].addObj.setValue('');
				}
            }
        }
    },
    cancel: function(){
        this.rowContainer.hide();
        this.targetRow = null;
        if (this.cfg.showAtTop) {
            //this.resetAddingRow();
        }
    },
    hide: function(){
        this.rowContainer.hide();
    }
};